const {conn}=require('../db');
const {Users,Pwd,inserData, updateDate}=require('../dao/sql');
var QcloudSms = require("qcloudsms_js");
const {to,tokenO}=require('./tkens')
const alipaySdk = require('../alipay.js')
const AlipayFormData=require('alipay-sdk/lib/form').default;
const axios =require('axios')
module.exports=router=(app)=>{
    app.post('/login',(req,res)=>{
        let tel=req.body.userTel;
        let pwd=req.body.userPwd;
        //查询用户是否存在
        conn.query(Users(),[tel],(err,rs)=>{
            if(err) throw err;
            if(rs.length>0){
                conn.query(Pwd(),[tel,pwd],(err,rs)=>{
                    if(err) throw err;
                    if(rs.length>0){
                        //手机号和密码都对
                        res.send({
                                data:rs[0],
                                msg:'登陆成功',
                                success:true
                            });
                    }else{
                        //密码不对
                        res.send({
                                msg:'密码错误',
                                success:false
                            });
                    }
                })
            }else{
                //手机号不存在
                res.send(
                    {
                        msg:'手机号不存在',
                        success:false
                    }
                );
            }
            
        });
        // let params={
        //     userTel:req.body.userTel,
        //     userPwd:req.body.userPwd
        // }
        // conn.query(Users(params),(err,rs)=>{
        //     if(err) throw err;
        //     if(rs.length>0){
        //         conn.query(Pwd(params),(err,rs)=>{
        //             if(err) throw err;
        //             if(rs.length>0){
        //                 //手机号和密码都对
        //                 res.send({
        //                     data:{
        //                         msg:rs[0]
        //                     }
        //                 });
        //             }else{
        //                 //密码不对
        //                 res.send({
        //                     data:{
        //                         msg:'密码错误'
        //                     }
        //                 });
        //             }
        //         })
        //     }else{
        //         //手机号不存在
        //         res.send({
        //             data:{
        //                 msg:'手机号不存在'
        //             }
        //         });
        //     }
            
        // });

    })
    app.post('/code',(req,res)=>{
        console.log(req.body.phone)
        let tel=req.body.phone
        // 短信应用SDK AppID
        var appid = 1400187558;  // SDK AppID是1400开头

        // 短信应用SDK AppKey
        var appkey = "dc9dc3391896235ddc2325685047edc7";

        // 需要发送短信的手机号码
        var phoneNumbers = [tel];

        // 短信模板ID，需要在短信应用中申请
        var templateId = 285590;  // NOTE: 这里的模板ID`7839`只是一个示例，真实的模板ID需要在短信控制台中申请

        // 签名
        var smsSign = "三人行慕课";  // NOTE: 这里的签名只是示例，请使用真实的已申请的签名, 签名参数使用的是`签名内容`，而不是`签名ID`

        // 实例化QcloudSms
        var qcloudsms = QcloudSms(appid, appkey);

        // 设置请求回调处理, 这里只是演示，用户需要自定义相应处理回调
        function callback(err, ress, resData) {
        if (err) {
        console.log("err: ", err);
        } else {
            console.log("request data: ", ress.req);
            console.log("response data: ", resData);
            res.send({
                success:true,
                data:ress.req.body.params[0]
            })
        }
        }
        var ssender = qcloudsms.SmsSingleSender();
        var params = [Math.floor(Math.random()*(9999-1000))+1000];
        ssender.sendWithParam(86, phoneNumbers[0], templateId,
          params, smsSign, "", "", callback);  // 签名参数不能为空串
    })
    app.post('/addUser',(req,res)=>{
        let tel=req.body.phone
        //查询用户是否存在
        conn.query(Users(),[tel],(err,rs)=>{
            if(err) throw err;
            if(rs.length>0){
                console.log(rs)
                res.send({
                    success:true,
                    msg:'登陆成功',
                    data:rs[0]
                })
            }else{
                conn.query(inserData(),[tel,'123456','https://img0.baidu.com/it/u=3503928812,2286755836&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500','普通用户',to(tel)],(errs,rss)=>{
                    conn.query(Users(),[tel],(e,r)=>{
                        if(e) throw e;
                        if(r.length>0){
                            console.log(r)
                            res.send({
                                success:true,
                                msg:'登陆成功',
                                data:r[0]
                            })
                        }       
                    })
                })
            }
        })
    })
    app.post('/reg',(req,res)=>{
        let tel=req.body.phone
        let pwd=req.body.pwd
        //查询用户是否存在
        conn.query(Users(),[tel],(err,rs)=>{
            if(err) throw err;
            if(rs.length>0){
                console.log(rs)
                res.send({
                    success:true,
                    msg:'登陆成功',
                    data:rs[0],
                    user:0
                })
            }else{
                pwd = pwd === '' ? '123456' : pwd
                conn.query(inserData(),[tel,pwd,'https://img0.baidu.com/it/u=3503928812,2286755836&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500','普通用户',to(tel)],(errs,rss)=>{
                    conn.query(Users(),[tel],(e,r)=>{
                        if(e) throw e;
                        if(r.length>0){
                            console.log(r)
                            res.send({
                                success:true,
                                msg:'登陆成功',
                                data:r[0],
                                user:1
                            })
                        }       
                    })
                })
            }
        })
    })
    app.post('/select',(req,res)=>{
        let tel=req.body.phone
        //查询用户是否存在
        conn.query(Users(),[tel],(err,rs)=>{
            if(err) throw err;
            if(rs.length>0){
                console.log(rs)
                res.send({
                    success:true,
                })
            }else{
                res.send({
                    success:false,
                    msg:'该用户不存在'
                })
            }
        })
    })
    app.post('/update',(req,res)=>{
        let tel=req.body.phone
        let pwd=req.body.pwd
        conn.query(Users(),[tel],(err,rs)=>{
            //用户的id
            let id=rs[0].id
            conn.query(updateDate(),[pwd,id],(err,rs)=>{
                if(err) throw err;
                res.send({
                    success:true,
                    msg:'修改成功'
                })
            })
        })
    })
    app.post('/addCart',(req,res)=>{
       let {id,price,num,sr,name}=req.body
       conn.query('select * from users where tel = ?',[tokenO(req.body).tel],(err,rs)=>{
            let uid = rs[0].id;
            let sid=id
            conn.query('select * from cart where sid = ?',[sid],(er,rss)=>{
                conn.query('select * from cart where uid = ? and sid = ?',[uid,sid],(e,r)=>{
                        if(r.length>0){
                            let nums=parseInt(r[0].num)+num
                            //说明用户添加过商品
                            conn.query('update cart set num = ? where id = ?',[nums,r[0].id],()=>{
                                res.send({
                                    success:true,
                                    msg:'添加成功'
                                })
                            })
                        }else{
                            let img = sr
                            conn.query('insert into cart (sid,price,num,img,uid,name) values (?,?,?,?,?,?)',[sid,price,num,img,uid,name],(err,rs)=>{
                                res.send({
                                    success:true,
                                    msg:'添加成功'
                                })
                            })
                        }
                })
            })
       })
    })
    app.post('/selectCart',(req,res)=>{
        conn.query('select * from users where tel = ?',[tokenO(req.body).tel],(err,rs)=>{
            let uid = rs[0].id;
            conn.query('select * from cart where uid = ?',[uid],(err,rs)=>{
                return res.send({
                    success:true,
                    data:rs
                })
            })
        })
    })
    app.post('/delete',(req,res)=>{
        conn.query('delete from cart where id = ?',[req.body.id],(err,rs)=>{
            res.send({
                success:true,
                msg:'删除成功'
            })
        })
    })
    app.post('/updates',(req,res)=>{
        conn.query('update cart set num=? where sid=? ',[req.body.num,req.body.sid],(err,rs)=>{
            res.send({
                success:true,
            })
        })
    })
    app.post('/addAddress',(req,res)=>{
        let {name,tel,province,city,county,areaCode,addressDetail,isDefault}=req.body
        
        conn.query(`select * from users where tel = ?`,[tokenO(req.body).tel],(err,rs)=>{
            let uid=rs[0].id;
            if(isDefault != 1){conn.query(`insert into addrs (name,tel,province,city,county,areaCode,addressDetail,isDefault,uid) values (?,?,?,?,?,?,?,?,?)`,[name,tel,province,city,county,areaCode,addressDetail,isDefault,uid],(erre,rss)=>{
                res.send({
                    success:true,
                    msg:'添加成功'
                })  
            })}else{
                conn.query(`select * from addrs where uid = ? and isDefault = ?`,[uid,isDefault],(e,r)=>{
                    let addrId = r[0].id;
                    conn.query(`update addrs set isDefault = ? where id = ?`,[0,addrId],(er,urs)=>{
                        conn.query(`insert into addrs (name,tel,province,city,county,areaCode,addressDetail,isDefault,uid) values (?,?,?,?,?,?,?,?,?)`,[name,tel,province,city,county,areaCode,addressDetail,isDefault,uid],()=>{
                            res.send({
                                success:true,
                                msg:'添加成功'
                            })  
                        })
                    })
                })
            }
        })

    })
    app.post('/getAddress',(req,res)=>{
        conn.query(`select * from users where tel = ?`,[tokenO(req.body).tel],(err,rs)=>{
            let uid=rs[0].id;
            conn.query(`select * from addrs where uid = ?`,[uid],(err,rs)=>{
                res.send({
                    data:rs,
                    msg:'查询成功',
                    success:true
                })
                
            })
        })
    })
    app.post('/updateAddress',(req,res)=>{
        let {id,name,tel,province,city,county,areaCode,addressDetail,isDefault}=req.body
        conn.query(`select * from users where tel = ?`,[tokenO(req.body).tel],(err,rs)=>{
            let uid=rs[0].id;
                conn.query(`select * from addrs where uid = ? and isDefault = ?`,[uid,isDefault],(e,r)=>{
                if(r.length === 1){
                    let addrId = r[0].id;
                    conn.query(`update addrs set isDefault = ? where id = ?`,[0,addrId],(er,urs)=>{
                        conn.query(`update addrs set name=?,tel=?,province=?,city=?,county=?,areaCode=?,addressDetail=?,isDefault=? where id = ?`,[name,tel,province,city,county,areaCode,addressDetail,isDefault,id],(error,rasou)=>{
                            res.send({
                                success:true,
                                msg:'修改成功', 
                            })  
                        })
                    })
                }else{
                    conn.query(`update addrs set name=?,tel=?,province=?,city=?,county=?,areaCode=?,addressDetail=?,isDefault=? where id = ?`,[name,tel,province,city,county,areaCode,addressDetail,isDefault,id],(el,rl)=>{
                        res.send({
                            success:true,
                            msg:'修改成功',
                        })  
                    })
                }

            })
        })
    })
    app.post('/deleteAddress',(req,res)=>{
        conn.query(`select * from users where tel = ?`,[tokenO(req.body).tel],(e,r)=>{
            let uid=r[0].id
            conn.query(`delete from addrs where id = ? and uid = ?`,[req.body.id,uid],(err,rs)=>{
                res.send({
                    success:true,
                    msg:'删除成功',
                })  
            })
        })
    })
    //生成订单
    app.post('/getOrder',(req,res)=>{
        let arr=req.body.arr
        //商品列表
        let name = []
        //总价格
        let price = 0
        //总数量
        let num = 0
        //订单号
        let orderId=randomNumber()
        arr.map(p=>{
            name.push(p.name);
            num +=parseInt(p.num);
            price +=parseInt(p.num) * parseInt(p.price);
        })
        conn.query(`select * from users where tel = ?`,[tokenO(req.body).tel],(e,r)=>{
            let uid =r[0].id
            conn.query(`insert into store_order (order_id,name,num,price,uid,status) values ('${orderId}','${name}','${num}','${price}','${uid}',${1})`,()=>{
                conn.query(`select * from store_order where uid = ${uid} and order_id=${orderId}`,(err,rs)=>{
                    res.send({
                        data:rs,
                        success:true
                    })
                })
            })
        })
        //生成订单号:规则:时间戳+6位随机数
        function setTimeDateFmt(s){
            return s < 10  ? '0' + s : s
        }
        function randomNumber(){
            const now = new Date();
            let month=now.getMonth() + 1;
            let day = now.getDate()
            let hour = now.getHours();
            let mintes = now.getMinutes();
            let seconds = now.getSeconds();
            month=setTimeDateFmt(month)
            day=setTimeDateFmt(day)
            hour=setTimeDateFmt(hour)
            mintes=setTimeDateFmt(mintes)
            seconds=setTimeDateFmt(seconds)
            let orderCode = now.getFullYear().toString() + month.toString()+ day.toString()+ hour.toString()+ mintes.toString()+ seconds.toString() + (Math.round(Math.random()* 1000000)).toString()
            return orderCode
        }
    })
    app.post('/selectOrder',(req,res)=>{
        console.log(req.body.order_id)
        conn.query(`select * from store_order where order_id = ?`,[req.body.order_id],(e,r)=>{
            console.log(r)
            res.send({
                data:{
                    success:true,
                    data:r
                }
            })
        })
    })
    app.post('/submitOrder',(req,res)=>{
        conn.query(`select * from users where tel = ?`,[tokenO(req.body).tel],(e,r)=>{
            let uid = r[0].id;
            conn.query(`select * from store_order where order_id = ? and uid = ?`,[req.body.order_id,uid],(err,rs)=>{
                let id = rs[0].id;
                conn.query(`update store_order set status= ?  where id = ?`,[2,id],()=>{
                    req.body.shopArr.forEach(e => {
                        conn.query(`delete from cart where id = ? and uid = ?`,[e,uid],()=>{
                        })
                    });
                    return res.send({
                        success:true,
                        msg:'删除成功'
                    })
                })
            })
        })
    })
    app.post('/payment',(req,res)=>{
        let {order_id,price,name} =req.body
        const formData = new AlipayFormData();
        //跳转到支付页面的url
        formData.setMethod('get');
        //支付时信息
        formData.addField('bizContent', {
            outTradeNo: order_id,//订单号
            productCode: 'FAST_INSTANT_TRADE_PAY',//写死的
            totalAmount: price,//价格
            subject: name,//商品名称
          });
        //支付失败或成功的跳转链接
        formData.addField('returnUrl', 'http://localhost:8080/#/pay');
        const result =alipaySdk.exec(
            'alipay.trade.page.pay',
            {},
            { formData: formData },
          );
        //对接支付宝成功，支付宝返回的数据
        result.then(resp=>{
            return res.send({
                data:{
                    success:true,
                    msg:'支付中',
                    payUrl:resp
                }
            })
        })
    })
    app.post('/getStatus',(req,res)=>{
        let {out_trade_no,trade_no}=req.body
        const formData = new AlipayFormData();
        //跳转到支付页面的url
        formData.setMethod('get');
        //支付时信息
        formData.addField('bizContent', {
                out_trade_no,
                trade_no
        });
        //返回一个promise
        const result =alipaySdk.exec(
        'alipay.trade.query',
        {},
        { formData: formData },
        );
        //后端请求支付宝
        result.then(resData=>{
            axios({
                method:'GET',
                url:resData
            }).then(data=>{
                let responseCode=data.data.alipay_trade_query_response;
                console.log()
                if(responseCode.code == '10000'){
                    switch( responseCode.trade_status){
                        case 'WAIT_BUYER_PAY':
                        res.send({
                            code:0,
                            msg:'交易创建'
                        })
                        break;
                        case 'TRADE_FINISHED':
                            conn.query(`select * from users where tel = ?`,[tokenO(req.body).tel],(e,r)=>{
                                let uid = r[0].id;
                                conn.query(`select * from store_order where uid = ? and order_id=?`,[uid,out_trade_no],(err,rs)=>{
                                    let id = rs[0].id;
                                    conn.query(`update store_order set status=? where id = ?`,[3,id],(err,rs)=>{
                                        res.send({
                                            code:2,
                                            msg:'支付成功'
                                        })
                                    })
                                })
                            })
                        break;
                        case 'TRADE_SUCCESS':
                            conn.query(`select * from users where tel = ?`,[tokenO(req.body).tel],(e,r)=>{
                                let uid = r[0].id;
                                conn.query(`select * from store_order where uid = ? and order_id=?`,[uid,out_trade_no],(err,rs)=>{
                                    let id = rs[0].id;
                                    conn.query(`update store_order set status=? where id = ?`,[3,id],(err,rs)=>{
                                        res.send({
                                            code:2,
                                            msg:'支付成功'
                                        })
                                    })
                                })
                            })

                        break;
                        case 'TRADE_CLOSED':
                            res.send({
                                code:1,
                                msg:'交易关闭'
                            })
                        break;
                    }
                }else if(responseCode.code == '40004'){
                    res.send({
                        data:{
                            code:4,
                            msg:'交易不存在'
                        }
                    })
                }
            }).catch(err=>{
                res.send({
                    data:{
                        code:500,
                        msg:'交易失败'
                    }
                })
            })
        })
    })
    app.post('/user',(req,res)=>{
        conn.query('select * from users',(e,r)=>{
            const index = r.findIndex(r=>tokenO(req.body).tel=== r.tel)
            r.splice(index,1)
            res.send({
                data:r
            })
        })
    })
}